<?php

namespace app\api\model;

use app\admin\model\vip\Code;
use app\exceptions\ApiException;
use ba\Exception;
use think\facade\Db;
use think\Model;

/**
 * Banner
 */
class MemberVipCard extends Model
{
    // 表名
    protected $name = 'member_vip_card';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    public function getMemberVipCardId($member_id, $type)
    {
        return self::where(['member_id' => $member_id, 'vip_type' => $type, 'status' => 1])->value('vip_card_id');
    }


    public function memberVipCard($params)
    {
        $member_id = $params['member_id'];
        $type = $params['type'] ?? 1;
        $map[] = ['mv.member_id','=',$member_id];
        if($type == 1){
            $map[] = ['mv.status','in',[0,1]];
        }else{
            $map[] = ['mv.status','=',2];
        }


        $member_vip_card = self::alias('mv')
            ->join('vip_card vc', 'vc.id = mv.vip_card_id')
            ->join('member m', 'm.id = mv.member_id')
            ->where($map)
            ->field(
                'mv.id,mv.nums,mv.expire_time,mv.vip_type,vc.name,vc.image,vc.use_type,vc.nums as total_nums,m.username,m.id_number,vc.book_notice,mv.status'
            )->order('mv.id desc')
            ->select()->toArray();

        if (!$member_vip_card) {
            return api_message();
        }

        foreach ($member_vip_card as &$val) {
            $val['expire_time'] = date("Y-m-d H:i:s", $val['expire_time']);
            $val['image'] = full_url($val['image']);
            if ($val['use_type'] == 2) {
                $val['total_nums'] = "无限";
            }
        }


        return api_message($member_vip_card);
    }



    public function canelVipCard($params){
        $member_vip_card_id = $params['member_vip_card_id'] ?? 0;
        $member_vip_card = self::where(['id' => $member_vip_card_id])->find();
        if(!$member_vip_card) throw new ApiException('会员卡不存在');
        if($member_vip_card['status'] != 0) throw new ApiException('已激活的卡不支持退款');
        //查询订单
        $order = (new VipOrder())->where(['id' => $member_vip_card['order_id']])->find();
        if(!$order) throw new ApiException('订单不存在');

        //执行退款
        try{
            Db::startTrans();
            (new MemberVipCard())->where(['id' => $member_vip_card_id])->delete();
            (new VipOrder())->where(['id' => $member_vip_card['order_id']])->update(['status'=>2,'update_time' => time()]);
            (new Pay())->refund($order['transaction_id'],$order['out_trade_no'],$order['price'],$order['price']);
            (new Code())->where(['number' => $member_vip_card['vip_code']])->update(['status' => 0]);
            Db::commit();
            return api_message([],'退款成功,请留意微信退款信息');
        }catch(Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }

}
